package com.app.base.service.common.listener;

import com.app.base.config.mq.RabbitConfig;
import com.app.base.utlis.verification.CodeUtils;
import com.app.base.utlis.verification.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RabbitListener(queues = RabbitConfig.DIRECT_QUEUE)
public class PhoneListener {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @RabbitHandler
    public void process(String message){
        if (StringUtils.isEmpty(redisTemplate.opsForValue().get(message))){
            String code = CodeUtils.code();
            redisTemplate.opsForValue().set(message, code.toLowerCase(),60, TimeUnit.SECONDS);
            try {
                String host = "https://dfsns.market.alicloudapi.com";
                String path = "/data/send_sms";
                String method = "POST";
                String appcode = "a880591aafe24214823a7db1e19f0d01";
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "APPCODE " + appcode);
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                Map<String, String> querys = new HashMap<String, String>();
                Map<String, String> bodys = new HashMap<String, String>();
                bodys.put("content", "code: "+ code);
                bodys.put("phone_number", message);
                bodys.put("template_id", "TPL_0000");
                HttpResponse response = HttpUtils.doPost(host,path,method,headers,querys,bodys);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

}
